package com.deer.wms.system.manage.web;

import com.deer.wms.project.root.util.RedisUtil;
import com.deer.wms.system.manage.model.DataDictDetail;
import com.deer.wms.system.manage.model.DataDictDetailCriteria;
import com.deer.wms.system.manage.service.DataDictDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;

import java.util.List;

/**
*
 * @author wei
 * @date 2019/11/25
 */
@Api(description = "数据字典详细信息api接口")
@RestController
@RequestMapping("/data/dict/details")
public class DataDictDetailController {

    @Autowired
    private DataDictDetailService dataDictDetailService;

    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/insert")
    public Result add(@RequestBody DataDictDetail dataDictDetail) {
        dataDictDetailService.save(dataDictDetail);
        removeRedisCache();
        return ResultGenerator.genSuccessResult();
    }

    private void removeRedisCache() {
        List<DataDictDetail> dataDictDetails = dataDictDetailService.list();
        for (DataDictDetail detail : dataDictDetails) {
            redisUtil.remove(detail.getDataDictCode() + "DataDictDetail");
        }
    }

    @GetMapping("/delete")
    public Result delete(Integer id) {
        dataDictDetailService.removeById(id);
        removeRedisCache();
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    public Result update(@RequestBody DataDictDetail dataDictDetail) {
        dataDictDetailService.updateById(dataDictDetail);
        removeRedisCache();
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/detail")
    public Result detail(@PathVariable Integer id) {
        DataDictDetail dataDictDetail = dataDictDetailService.getById(id);
        return ResultGenerator.genSuccessResult(dataDictDetail);
    }

    @GetMapping("/list")
    public Result list(DataDictDetailCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<DataDictDetail> list = dataDictDetailService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/findBydDataDictCode")
    public Result findBydDataDictCode(String dataDictCode) {
//        List<DataDictDetail> list = (List<DataDictDetail>) redisUtil.get(dataDictCode+"DataDictDetail");
//        if(list==null || list.size()==0){
        List<DataDictDetail> list = dataDictDetailService.findBydDataDictCode(dataDictCode);
//            redisUtil.set(dataDictCode+"DataDictDetail",list);
//        }
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }
}
